package com.apanal.qlife.common.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

/**
 * web工具类
 * 
 * 
 * @author shuliangxing
 * 
 * @date 2015-10-22下午6:34:55
 */
public class WebUtils {

	/**
	 * 判断是否是ajax请求
	 * 
	 * @param req
	 * @return
	 */
	public static boolean isAjaxRequest(HttpServletRequest req) {
		if (req.getHeader("accept").indexOf("application/json") > -1
				|| (req.getHeader("X-Requested-With") != null && req.getHeader(
						"X-Requested-With").indexOf("XMLHttpRequest") > -1)) {
			return true;
		}
		return false;
	}

	/**
	 * 是否是ie浏览器
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isIe(HttpServletRequest request) {
		if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0
				|| request.getHeader("User-Agent").toUpperCase()
						.indexOf("TRIDENT") > 0) {
			return true;
		}
		return false;
	}

	/**
	 * response返回网络流
	 * 
	 * @param data
	 *            返回数据
	 * @param response
	 * @throws IOException
	 */
	public static void sendData(String data, HttpServletResponse response)
			throws IOException {
		PrintWriter out = response.getWriter();
		out.write(data);
		out.flush();
		out.close();
	}

	/**
	 * 获取简短的url(uri去掉contextPath和参数部分,并去掉开头的斜杠)
	 * 
	 * @param request
	 * @return
	 */
	public static String getShortUrl(HttpServletRequest request) {
		String uri = request.getRequestURI();
		String contextPath = request.getContextPath();
		// 服务器部署时contextPath有可能为空
		if (!StringUtils.isEmpty(contextPath)) {
			uri = uri
					.substring(uri.indexOf(contextPath) + contextPath.length());
		}

		// 去掉开头斜杠
		if (uri.startsWith("/")) {
			uri = uri.substring(1);
		}
		return uri;
	}
}
